import json

from funcall.AbstractFunCall import AbstractFunCall, fun_call_log_debug, FUN_CALL_REMARK

from conf.config import AppConf
from funcall.FuncallInfo import FuncallInfo, funcall_info_to_mysql
from funcalltools.file_utils import fc_write_file, fc_read_file
from funcall.funcall_result import FuncallResult
from funcalltools.json_utils import to_json
from utils.log_utils import log_title


def baidu_search(query: str) -> str:
    from baidusearch.baidusearch import search
    results_list = search(query, num_results=20,debug=1)
    print(f"\n\n\nresults_list={results_list}")
    web_result = ""
    if results_list:
        for results_item in results_list:
            title = results_item.get("title", "")
            content = results_item.get("abstract", "")
            url = results_item.get("url", "")
            if title and content:
                web_result = (
                        web_result + "标题：" + title + "\n" + "内容：" + content + "\n\n"+"链接:"+url+"\n\n"
                )
    print(web_result)
    return web_result

class baidu_search_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "baidu_search"
        self.description = "互联网搜索引擎,百度搜索"

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "search_text": {
                    "type": "string",
                    "description": f"要搜索的文本内容(工具中使用了 python的 baidusearch 库进行的搜索, 搜索的结果内容存放在返回json的content中,配合'access_www'工具去查找你想知道的内容)"
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "search_text"
        ]

    def action(self, jsonRoot):
        arg_tmp = jsonRoot['search_text']
        funcallInfo = FuncallInfo(description="baidu_search", req_args=arg_tmp)
        funcallInfo.remark=jsonRoot['remark']
        funcall_info_to_mysql(funcallInfo)

        from baidusearch.baidusearch import search
        results = search(arg_tmp, num_results=20)
        # import pandas as pd
        # df=pd.DataFrame(results)
        # print(df.head())
        content_tmp=to_json(results)
        funcallInfo.log_text=content_tmp
        fun_call_log_debug(funcallInfo)
        return FuncallResult(msg="成功",content=content_tmp).to_json()


if __name__ == '__main__':
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = baidu_search_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {"search_text": "solon是什么","remark": 'test'}
    result = cw.call(args)

    # 打印结果
    print((result))
